// 侧边栏脚本
class SmartAssistant {
    constructor() {
        this.currentSection = 'config';
        this.selectedText = '';
        this.pageContent = null;
        this.selectionMonitorInterval = null;
        this.isManualEditing = false; // 标记用户是否正在手动编辑原文框
        this.isClearingManually = false; // 标记是否正在手动清空
        this.testedProviders = new Set(); // 记录已测试通过的服务商
        this.availableFreeModels = []; // 存储可用的免费模型
        
        this.init();
        
        // 页面卸载时清理监听器
        window.addEventListener('beforeunload', () => {
            this.stopTextSelectionMonitor();
        });
    }
    
    async init() {
        // 等待配置管理器初始化
        await window.configManager.init();
        this.bindEvents();
        this.updateConfigUI();
        
        // 检查已配置的服务商
        await this.checkConfiguredProviders();
        
        // 检查是否已配置
        if (window.configManager.isConfigured()) {
            this.showSection('main');
            // 启动实时监听选中文本
            this.startTextSelectionMonitor();
            // 初始化翻译模型选择器
            this.initTranslateModelSelect();
        } else {
            this.showSection('config');
        }
    }
    
    // 更新配置界面
    updateConfigUI() {
        const config = window.configManager.config;
        
        // 更新可用模型列表
        this.updateAvailableModels();
        
        // 更新模型选择
        const modelSelect = document.getElementById('model-select');
        if (modelSelect && config.model) {
            // 检查当前配置的模型是否在可用列表中
            const option = modelSelect.querySelector(`option[value="${config.model}"]`);
            if (option) {
                modelSelect.value = config.model;
            }
        }
        
        // 更新最大token数
        const maxTokensInput = document.getElementById('max-tokens');
        if (maxTokensInput) {
            maxTokensInput.value = config.maxTokens;
        }
        
        // 更新复选框
        const autoTranslateCheckbox = document.getElementById('auto-translate');
        if (autoTranslateCheckbox) {
            autoTranslateCheckbox.checked = config.autoTranslate;
        }
        
        const autoSummarizeCheckbox = document.getElementById('auto-summarize');
        if (autoSummarizeCheckbox) {
            autoSummarizeCheckbox.checked = config.autoSummarize;
        }
        
        // 更新多服务商配置
        this.updateProvidersUI();
        
        // 更新状态显示
        this.updateConfigStatus();
    }

    // 更新多服务商配置界面
    updateProvidersUI() {
        const config = window.configManager.config;
        const providers = config.providers || {};
        
        // 更新各个服务商的配置
        Object.keys(providers).forEach(providerName => {
            const provider = providers[providerName];
            
            // 更新API密钥
            const apiKeyInput = document.getElementById(`${providerName}-api-key`);
            if (apiKeyInput) {
                apiKeyInput.value = provider.apiKey || '';
            }
            
            // 更新API地址
            const baseUrlInput = document.getElementById(`${providerName}-base-url`);
            if (baseUrlInput) {
                baseUrlInput.value = provider.baseUrl || '';
            }
            
            // 更新状态显示
            const statusElement = document.getElementById(`${providerName}-status`);
            if (statusElement) {
                if (provider.configured && provider.apiKey) {
                    statusElement.textContent = '已配置';
                    statusElement.className = 'provider-status configured';
                } else {
                    statusElement.textContent = '未配置';
                    statusElement.className = 'provider-status';
                }
            }
        });
    }
    
    // 更新配置状态显示
    updateConfigStatus() {
        const config = window.configManager.config;
        const providers = config.providers || {};
        
        const configStatusValue = document.getElementById('config-status-value');
        const apiKeyStatus = document.getElementById('api-key-status');
        
        if (configStatusValue) {
            if (window.configManager.isConfigured()) {
                configStatusValue.textContent = '已配置';
                configStatusValue.className = 'status-value success';
            } else {
                configStatusValue.textContent = '未配置';
                configStatusValue.className = 'status-value error';
            }
        }
        
        if (apiKeyStatus) {
            // 检查已配置的服务商数量
            const configuredProviders = Object.values(providers).filter(p => p.configured);
            if (configuredProviders.length > 0) {
                apiKeyStatus.textContent = `已配置${configuredProviders.length}个服务商`;
                apiKeyStatus.className = 'status-value success';
            } else {
                apiKeyStatus.textContent = '未配置';
                apiKeyStatus.className = 'status-value error';
            }
        }
    }
    
    // 绑定事件
    bindEvents() {
        // 配置相关
        document.getElementById('save-config').addEventListener('click', () => this.saveConfig());
        document.getElementById('reset-config').addEventListener('click', () => this.resetConfig());
        
        // API测试按钮
        document.getElementById('test-moonshot-btn').addEventListener('click', () => this.testApiConnection('moonshot'));
        document.getElementById('test-openai-btn').addEventListener('click', () => this.testApiConnection('openai'));
        document.getElementById('test-anthropic-btn').addEventListener('click', () => this.testApiConnection('anthropic'));
        
        // 密码可见性切换按钮
        document.querySelectorAll('.toggle-password-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const targetId = e.target.getAttribute('data-target');
                this.toggleApiKeyVisibility(targetId);
            });
        });
        
        // 标签页切换
        document.getElementById('translate-tab').addEventListener('click', () => this.switchTab('translate'));
        document.getElementById('summarize-tab').addEventListener('click', () => this.switchTab('summarize'));
        document.getElementById('settings-tab').addEventListener('click', () => this.showSettingsSection());
        
        // 翻译功能
        const translateBtn = document.getElementById('translate-btn');
        const clearBtn = document.getElementById('clear-btn');
        const copyBtn = document.getElementById('copy-translation-btn');
        
        if (translateBtn) {
            translateBtn.addEventListener('click', () => this.translateText());
        } else {
            console.error('翻译按钮未找到');
        }
        
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                console.log('清空按钮被点击');
                this.clearTranslation();
            });
        } else {
            console.error('清空按钮未找到');
        }
        
        if (copyBtn) {
            copyBtn.addEventListener('click', () => this.copyTranslation());
        } else {
            console.error('复制按钮未找到');
        }
        
        // 翻译模型选择
        document.getElementById('translate-model-select').addEventListener('change', (e) => {
            console.log('翻译模型已切换为:', e.target.value);
            this.updateModelStatus(e.target.value);
        });
        
        // 总结功能
        document.getElementById('summarize-page-btn').addEventListener('click', () => this.startSummarizing());
        document.getElementById('new-summarize-btn').addEventListener('click', () => this.newSummarize());
        
        // 原文框交互事件
        const originalTextElement = document.getElementById('original-text');
        if (originalTextElement) {
            // 用户开始编辑时暂停自动更新
            originalTextElement.addEventListener('focus', () => {
                this.isManualEditing = true;
            });
            
            // 用户停止编辑后恢复自动更新
            originalTextElement.addEventListener('blur', () => {
                setTimeout(() => {
                    this.isManualEditing = false;
                }, 1000); // 1秒后恢复自动更新
            });
            
            // 实时语言检测
            originalTextElement.addEventListener('input', () => {
                this.updateLanguageDetection();
            });
            
            // 粘贴事件也触发语言检测
            originalTextElement.addEventListener('paste', () => {
                setTimeout(() => {
                    this.updateLanguageDetection();
                }, 100);
            });
        }
        
        document.getElementById('resummarize-btn').addEventListener('click', () => this.summarizePage());
        document.getElementById('copy-summary-btn').addEventListener('click', () => this.copySummary());
        
        // 设置功能
        document.getElementById('edit-settings').addEventListener('click', () => this.showSection('config'));
        document.getElementById('export-config').addEventListener('click', () => this.exportConfig());
        document.getElementById('import-config').addEventListener('click', () => this.importConfig());
        document.getElementById('back-from-settings').addEventListener('click', () => this.showSection('main'));
        
        // 回车键保存配置
        document.getElementById('api-key').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.saveConfig();
            }
        });
    }
    
    // 保存配置
    async saveConfig() {
        const modelSelect = document.getElementById('model-select');
        const maxTokensInput = document.getElementById('max-tokens');
        const autoTranslateCheckbox = document.getElementById('auto-translate');
        const autoSummarizeCheckbox = document.getElementById('auto-summarize');
        
        // 收集多服务商配置
        const providers = {};
        const providerNames = ['moonshot', 'openai', 'anthropic'];
        
        providerNames.forEach(providerName => {
            const apiKeyInput = document.getElementById(`${providerName}-api-key`);
            const baseUrlInput = document.getElementById(`${providerName}-base-url`);
            
            if (apiKeyInput && baseUrlInput) {
                const apiKey = apiKeyInput.value.trim();
                const baseUrl = baseUrlInput.value.trim();
                
                providers[providerName] = {
                    apiKey: apiKey,
                    baseUrl: baseUrl,
                    configured: !!apiKey
                };
            }
        });
        
        // 检查是否有至少一个服务商已配置
        const hasConfiguredProvider = Object.values(providers).some(p => p.configured);
        
        const config = {
            model: modelSelect.value,
            maxTokens: parseInt(maxTokensInput.value),
            autoTranslate: autoTranslateCheckbox.checked,
            autoSummarize: autoSummarizeCheckbox.checked,
            isConfigured: hasConfiguredProvider,
            providers: providers,
            // 向后兼容：使用moonshot的API密钥作为主API密钥
            apiKey: providers.moonshot?.apiKey || ''
        };
        
        const success = await window.configManager.saveConfig(config);
        
        if (success) {
            this.updateConfigStatus();
            this.showSuccess('配置保存成功');
            
            // 保存成功后，重新检查所有已配置服务商的连通性
            await this.checkConfiguredProviders();
            
            // 如果配置完成，显示主界面
            if (hasConfiguredProvider) {
                setTimeout(() => {
                    this.showSection('main');
                    this.startTextSelectionMonitor();
                    this.initTranslateModelSelect();
                }, 1500);
            }
        } else {
            this.showError('保存配置失败');
        }
    }
    
    // 重置配置
    async resetConfig() {
        try {
            if (confirm('确定要重置所有配置吗？此操作不可撤销。')) {
                const success = await window.configManager.resetConfig();
                if (success) {
                    // 清空已测试的服务商状态
                    this.testedProviders.clear();
                    
                    // 清空免费模型列表
                    this.availableFreeModels = [];
                    
                    // 更新配置界面
                    this.updateConfigUI();
                    this.updateConfigStatus();
                    
                    // 重新更新可用模型列表
                    this.updateAvailableModels();
                    
                    this.showSuccess('配置已重置');
                } else {
                    this.showError('重置配置失败');
                }
            }
        } catch (error) {
            console.error('重置配置失败:', error);
            this.showError('重置配置失败');
        }
    }
    
    // 切换API密钥可见性
    toggleApiKeyVisibility(inputId) {
        const input = document.getElementById(inputId);
        if (!input) return;
        
        // 查找同一个容器内的按钮
        const container = input.parentElement; // .input-with-button
        const button = container.querySelector('.toggle-password-btn');
        
        if (!button) return;
        
        if (input.type === 'password') {
            input.type = 'text';
            button.textContent = '🙈';
        } else {
            input.type = 'password';
            button.textContent = '👁️';
        }
    }
    
    // 显示设置界面
    showSettingsSection() {
        this.showSection('settings');
        this.updateSettingsDisplay();
    }
    
    // 更新设置显示
    updateSettingsDisplay() {
        const config = window.configManager.config;
        
        // 更新设置显示
        const currentModel = document.getElementById('current-model');
        const currentMaxTokens = document.getElementById('current-max-tokens');
        const currentApiStatus = document.getElementById('current-api-status');
        const currentAutoTranslate = document.getElementById('current-auto-translate');
        const currentAutoSummarize = document.getElementById('current-auto-summarize');
        
        if (currentModel) currentModel.textContent = config.model;
        if (currentMaxTokens) currentMaxTokens.textContent = config.maxTokens;
        if (currentApiStatus) {
            currentApiStatus.textContent = window.configManager.isConfigured() ? '已配置' : '未配置';
        }
        if (currentAutoTranslate) currentAutoTranslate.textContent = config.autoTranslate ? '开启' : '关闭';
        if (currentAutoSummarize) currentAutoSummarize.textContent = config.autoSummarize ? '开启' : '关闭';
    }
    
    // 导出配置
    exportConfig() {
        try {
            const configData = window.configManager.exportConfig();
            const blob = new Blob([JSON.stringify(configData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'smart-assistant-config.json';
            link.click();
            URL.revokeObjectURL(url);
            this.showSuccess('配置已导出');
        } catch (error) {
            console.error('导出配置失败:', error);
            this.showError('导出配置失败');
        }
    }
    
    // 导入配置
    importConfig() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        input.onchange = async (e) => {
            const file = e.target.files[0];
            if (file) {
                try {
                    const text = await file.text();
                    const configData = JSON.parse(text);
                    const success = await window.configManager.importConfig(configData);
                    if (success) {
                        this.updateConfigUI();
                        this.updateConfigStatus();
                        this.showSuccess('配置导入成功');
                    } else {
                        this.showError('导入配置失败');
                    }
                } catch (error) {
                    console.error('导入配置失败:', error);
                    this.showError('配置文件格式错误');
                }
            }
        };
        input.click();
    }
    
    // 切换标签页
    switchTab(tabName) {
        // 移除所有标签的激活状态
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
        
        // 激活当前标签
        document.getElementById(`${tabName}-tab`).classList.add('active');
        document.getElementById(`${tabName}-content`).classList.add('active');
        
        // 根据不同标签页管理监听状态
        if (tabName === 'translate') {
            // 切换到翻译标签页时启动监听并初始化翻译模型选择
            if (!this.selectionMonitorInterval) {
                this.startTextSelectionMonitor();
            }
            this.initTranslateModelSelect();
        } else {
            // 切换到其他标签页时停止监听以节省性能
            this.stopTextSelectionMonitor();
        }
        
        // 如果切换到总结标签页，重置状态
        if (tabName === 'summarize') {
            this.resetSummarizeSection();
        }
    }
    
    // 重置翻译界面
    resetTranslateSection() {
        this.selectedText = '';
        document.getElementById('original-text').textContent = '';
        document.getElementById('translated-text').textContent = '';
        
        // 重置语言检测显示
        this.updateLanguageDetection();
    }
    
    // 重置总结界面
    resetSummarizeSection() {
        this.pageContent = null;
        document.getElementById('summarize-prompt').style.display = 'block';
        document.getElementById('summarize-loading').style.display = 'none';
        document.getElementById('summarize-result').style.display = 'none';
        document.getElementById('page-title').textContent = '';
        document.getElementById('summary-text').textContent = '';
    }
    
    // 清空翻译内容
    clearTranslation() {
        console.log('执行清空翻译操作');
        
        // 设置手动清空标志，暂停自动监听
        this.isClearingManually = true;
        
        const originalTextElement = document.getElementById('original-text');
        const translatedTextElement = document.getElementById('translated-text');
        
        if (originalTextElement) {
            originalTextElement.textContent = '';
            console.log('原文已清空');
        } else {
            console.error('未找到原文元素');
        }
        
        if (translatedTextElement) {
            translatedTextElement.textContent = '';
            console.log('译文已清空');
        } else {
            console.error('未找到译文元素');
        }
        
        this.selectedText = '';
        
        // 隐藏语言方向显示
        const translationDirection = document.getElementById('translation-direction');
        if (translationDirection) {
            translationDirection.style.display = 'none';
            translationDirection.classList.remove('active');
            console.log('语言方向显示已隐藏');
        }
        
        // 隐藏错误消息
        this.hideError();
        
        // 尝试清除页面选中状态
        try {
            chrome.runtime.sendMessage({ type: 'CLEAR_SELECTION' });
            console.log('已发送清除页面选中状态的请求');
        } catch (error) {
            console.log('清除页面选中状态失败:', error);
        }
        
        // 3秒后恢复自动监听（给用户足够时间进行其他操作）
        setTimeout(() => {
            this.isClearingManually = false;
            console.log('恢复自动监听选中文本');
        }, 3000);
        
        console.log('清空操作完成');
    }

    // 初始化翻译模型选择器
    initTranslateModelSelect() {
        // 先更新可用模型列表
        this.updateAvailableModels();
        
        const translateModelSelect = document.getElementById('translate-model-select');
        if (translateModelSelect && window.configManager) {
            // 尝试设置为全局配置的模型
            const currentModel = window.configManager.getModel();
            if (currentModel) {
                // 检查当前模型是否在可用列表中
                const option = translateModelSelect.querySelector(`option[value="${currentModel}"]`);
                if (option) {
                    translateModelSelect.value = currentModel;
                }
            }
            
            // 更新模型状态显示
            if (translateModelSelect.value) {
                this.updateModelStatus(translateModelSelect.value);
            }
        }
    }

    // 更新模型状态指示器
    updateModelStatus(modelValue) {
        const statusElement = document.getElementById('model-status-text');
        const currentModelElement = document.getElementById('current-translate-model');

        const providerInfo = this.getModelProviderInfo(modelValue);
        
        // 检查是否为免费模型 - 改进的检测逻辑
        const isFreeModel = this.isModelFree(modelValue);
        
        // 更新状态指示器
        if (statusElement) {
            if (isFreeModel) {
                statusElement.textContent = `🆓 ${providerInfo.provider} 免费`;
                statusElement.className = 'model-status-free';
            } else {
                statusElement.textContent = `💰 ${providerInfo.provider} 付费`;
                statusElement.className = 'model-status-paid';
            }
        }

        // 更新当前模型显示
        if (currentModelElement) {
            const modelDisplayName = this.getModelDisplayName(modelValue);
            currentModelElement.textContent = `当前模型: ${modelDisplayName}`;
        }
    }

    // 检查模型是否为免费模型
    isModelFree(modelValue) {
        if (!modelValue) return false;
        
        // 1. 首先检查模型名是否包含免费关键词
        const nameContainsFree = modelValue.includes('free') || modelValue.includes('lite');
        
        // 2. 检查是否在动态检测到的免费模型列表中
        const isInFreeModelsList = this.availableFreeModels && 
            this.availableFreeModels.some(freeModel => freeModel.id === modelValue);
        
        return nameContainsFree || isInFreeModelsList;
    }

    // 获取模型的显示名称
    getModelDisplayName(modelValue, isShort = false) {
        const modelNames = {
            'moonshot-v1-8k': isShort ? 'moonshot-v1-8k' : 'moonshot-v1-8k (推荐)',
            'moonshot-v1-32k': 'moonshot-v1-32k',
            'moonshot-v1-128k': 'moonshot-v1-128k',
            'gpt-4o-mini': 'GPT-4o Mini',
            'gpt-4o': 'GPT-4o',
            'gpt-3.5-turbo': isShort ? 'GPT-3.5' : 'GPT-3.5 Turbo',
            'claude-3-haiku': isShort ? 'Claude Haiku' : 'Claude 3 Haiku',
            'claude-3-sonnet': isShort ? 'Claude Sonnet' : 'Claude 3 Sonnet',
            'claude-3-opus': isShort ? 'Claude Opus' : 'Claude 3 Opus',
            // 免费模型
            'kimi-free-api': isShort ? 'Kimi Free' : 'Kimi Free API 🆓',
            'kimi-free': isShort ? 'Kimi Free' : 'Kimi Free 🆓',
            'moonshot-free': isShort ? 'Moonshot Free' : 'Moonshot Free 🆓',
            'kimi-lite': isShort ? 'Kimi Lite' : 'Kimi Lite 🆓',
            'moonshot-lite': isShort ? 'Moonshot Lite' : 'Moonshot Lite 🆓'
        };
        
        return modelNames[modelValue] || modelValue;
    }
    
    // 获取适合下拉框显示的模型名称
    getSelectOptionText(modelValue, isFree = false) {
        const baseNames = {
            'moonshot-v1-8k': 'moonshot-v1-8k',
            'moonshot-v1-32k': 'moonshot-v1-32k', 
            'moonshot-v1-128k': 'moonshot-v1-128k',
            'gpt-4o-mini': 'GPT-4o Mini',
            'gpt-4o': 'GPT-4o',
            'gpt-3.5-turbo': 'GPT-3.5 Turbo',
            'claude-3-haiku': 'Claude Haiku',
            'claude-3-sonnet': 'Claude Sonnet', 
            'claude-3-opus': 'Claude Opus'
        };
        
        const baseName = baseNames[modelValue] || modelValue;
        return isFree ? `${baseName} 🆓` : `${baseName} 💰`;
    }

    // 获取模型的服务商信息
    getModelProviderInfo(modelValue) {
        if (modelValue.startsWith('moonshot-')) {
            return { provider: 'Moonshot', icon: '🚀' };
        } else if (modelValue.startsWith('gpt-')) {
            return { provider: 'OpenAI', icon: '🤖' };
        } else if (modelValue.startsWith('claude-')) {
            return { provider: 'Anthropic', icon: '🧠' };
        } else {
            return { provider: 'Unknown', icon: '❓' };
        }
    }

    // 检测文本语言
    detectLanguage(text) {
        // 去除空格和标点符号进行检测
        const cleanText = text.replace(/[^\w\u4e00-\u9fff\u3400-\u4dbf]/g, '');
        
        // 统计中文字符数量
        const chineseChars = cleanText.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g);
        const chineseCount = chineseChars ? chineseChars.length : 0;
        
        // 统计英文字符数量
        const englishChars = cleanText.match(/[a-zA-Z]/g);
        const englishCount = englishChars ? englishChars.length : 0;
        
        // 统计日文假名字符数量
        const japaneseChars = cleanText.match(/[\u3040-\u309f\u30a0-\u30ff]/g);
        const japaneseCount = japaneseChars ? japaneseChars.length : 0;
        
        // 统计韩文字符数量
        const koreanChars = cleanText.match(/[\uac00-\ud7af]/g);
        const koreanCount = koreanChars ? koreanChars.length : 0;
        
        const totalChars = cleanText.length;
        
        // 如果文本太短，默认为英文
        if (totalChars < 3) {
            return 'en';
        }
        
        // 计算各语言占比
        const chineseRatio = chineseCount / totalChars;
        const englishRatio = englishCount / totalChars;
        const japaneseRatio = japaneseCount / totalChars;
        const koreanRatio = koreanCount / totalChars;
        
        // 语言检测逻辑
        if (chineseRatio > 0.3) {
            return 'zh'; // 中文
        } else if (japaneseRatio > 0.2) {
            return 'ja'; // 日文
        } else if (koreanRatio > 0.2) {
            return 'ko'; // 韩文
        } else if (englishRatio > 0.5) {
            return 'en'; // 英文
        } else {
            // 混合语言或其他语言，优先级：中文 > 英文 > 其他
            if (chineseCount > englishCount) {
                return 'zh';
            } else {
                return 'en';
            }
        }
    }
    
    // 生成翻译提示词
    generateTranslationPrompt(sourceLanguage, text) {
        let systemContent = '';
        let userContent = '';
        
        switch (sourceLanguage) {
            case 'zh':
                systemContent = '你是一个专业的翻译助手。请将用户提供的中文文本翻译成英文，保持原文的意思、语气和风格。翻译要准确、自然、符合英文表达习惯。';
                userContent = `请将以下中文翻译成英文：\n\n${text}`;
                break;
            case 'ja':
                systemContent = '你是一个专业的翻译助手。请将用户提供的日文文本翻译成中文，保持原文的意思、语气和风格。翻译要准确、自然、符合中文表达习惯。';
                userContent = `请将以下日文翻译成中文：\n\n${text}`;
                break;
            case 'ko':
                systemContent = '你是一个专业的翻译助手。请将用户提供的韩文文本翻译成中文，保持原文的意思、语气和风格。翻译要准确、自然、符合中文表达习惯。';
                userContent = `请将以下韩文翻译成中文：\n\n${text}`;
                break;
            case 'en':
            default:
                systemContent = '你是一个专业的翻译助手。请将用户提供的英文文本翻译成中文，保持原文的意思、语气和风格。翻译要准确、自然、符合中文表达习惯。';
                userContent = `请将以下英文翻译成中文：\n\n${text}`;
                break;
        }
        
        return { systemContent, userContent };
    }

    // 启动实时监听选中文本
    startTextSelectionMonitor() {
        // 每500ms检查一次页面选中的文本
        this.selectionMonitorInterval = setInterval(async () => {
            // 如果用户正在手动编辑或正在手动清空，跳过自动更新
            if (this.isManualEditing || this.isClearingManually) {
                return;
            }
            
            try {
                const response = await chrome.runtime.sendMessage({ type: 'GET_SELECTION' });
                if (response && response.success && response.text && response.text.trim()) {
                    const currentSelection = response.text.trim();
                    // 只有当选中文本与当前原文框内容不同时才更新
                    const originalTextElement = document.getElementById('original-text');
                    if (originalTextElement && currentSelection !== originalTextElement.textContent.trim()) {
                        originalTextElement.textContent = currentSelection;
                        this.selectedText = currentSelection;
                        
                        // 自动选中文本后也更新语言检测
                        this.updateLanguageDetection();
                    }
                }
            } catch (error) {
                // 静默处理错误，避免频繁的错误日志
            }
        }, 500);
    }

    // 停止监听选中文本
    stopTextSelectionMonitor() {
        if (this.selectionMonitorInterval) {
            clearInterval(this.selectionMonitorInterval);
            this.selectionMonitorInterval = null;
        }
    }
    
    // 开始新总结
    newSummarize() {
        this.resetSummarizeSection();
    }
    
    // 翻译文本
    async translateText() {
        const originalTextElement = document.getElementById('original-text');
        const originalText = originalTextElement.textContent.trim();
        const translateBtn = document.getElementById('translate-btn');
        const translatedTextElement = document.getElementById('translated-text');
        const translateModelSelect = document.getElementById('translate-model-select');
        
        if (!originalText) {
            this.showError('请输入要翻译的文本');
            return;
        }
        
        // 检查配置
        const config = window.configManager.config;
        if (!window.configManager.isConfigured()) {
            this.showError('请先配置API密钥');
            this.showSection('config');
            return;
        }
        
        // 获取选中的模型
        const selectedModel = translateModelSelect.value;
        if (!selectedModel) {
            this.showError('请选择翻译模型');
            return;
        }
        
        // 检查是否有正在进行的请求
        if (translateBtn.disabled) {
            this.showError('正在处理中，请稍候...');
            return;
        }
        
        try {
            // 更新UI状态
            translateBtn.disabled = true;
            translateBtn.textContent = '翻译中...';
            translatedTextElement.textContent = '正在翻译，请稍候...';
            this.hideError();
            
            // 检测语言
            const detectedLang = this.detectLanguage(originalText);
            console.log('检测到的语言:', detectedLang);
            
            // 生成翻译提示词
            const { systemContent, userContent } = this.generateTranslationPrompt(detectedLang, originalText);
            
            const messages = [
                {
                    role: 'system',
                    content: systemContent
                },
                {
                    role: 'user',
                    content: userContent
                }
            ];
            
            console.log('发送翻译请求:', { model: selectedModel, messages });
            
            // 调用API
            const response = await chrome.runtime.sendMessage({
                type: 'CALL_AI_API',
                data: {
                    messages: messages,
                    model: selectedModel,
                    maxTokens: config.maxTokens,
                    providers: config.providers
                }
            });
            
            if (response.success) {
                translatedTextElement.textContent = response.data;
                this.showSuccess('翻译完成');
                console.log('翻译成功:', response.data);
            } else {
                console.error('翻译失败:', response.error);
                
                // 特殊处理频率限制错误
                if (this.isRateLimitError(response.error)) {
                    this.handleRateLimitError(response.error);
                } else {
                    translatedTextElement.textContent = '';
                    this.showError(`翻译失败: ${response.error}`);
                }
            }
            
        } catch (error) {
            console.error('翻译过程出错:', error);
            translatedTextElement.textContent = '';
            
            // 特殊处理频率限制错误
            if (this.isRateLimitError(error.message)) {
                this.handleRateLimitError(error.message);
            } else {
                this.showError(`翻译失败: ${error.message}`);
            }
        } finally {
            // 恢复UI状态
            translateBtn.disabled = false;
            translateBtn.textContent = '翻译';
        }
    }
    
    // 检查是否是频率限制错误
    isRateLimitError(errorMessage) {
        const message = errorMessage.toLowerCase();
        return message.includes('rate limit') || 
               message.includes('rpm') || 
               message.includes('请稍后重试') ||
               message.includes('调用过于频繁') ||
               message.includes('频率超限');
    }

    // 处理频率限制错误
    handleRateLimitError(errorMessage) {
        console.log('检测到频率限制错误:', errorMessage);
        
        // 提取等待时间
        const waitMatch = errorMessage.match(/(\d+)\s*秒/);
        const waitTime = waitMatch ? parseInt(waitMatch[1]) : 5;
        
        // 显示友好的错误信息和倒计时
        this.showRateLimitWarning(waitTime);
        
        // 开始倒计时
        this.startRetryCountdown(waitTime);
    }

    // 显示频率限制警告
    showRateLimitWarning(waitTime) {
        const errorElement = document.getElementById('error-message');
        if (errorElement) {
            errorElement.innerHTML = `
                <div class="rate-limit-warning">
                    <h4>🚦 API调用过于频繁</h4>
                    <p>您的账户达到了API调用频率限制。为了确保服务稳定，请稍等片刻。</p>
                    <div class="countdown-info">
                        <span>系统将在 <strong id="countdown-timer">${waitTime}</strong> 秒后自动重试</span>
                    </div>
                    <div class="rate-limit-tips">
                        <p><strong>💡 小贴士：</strong></p>
                        <ul>
                            <li>避免频繁切换模型或重复提交相同请求</li>
                            <li>考虑升级到更高配额的API套餐</li>
                            <li>使用较短的文本进行翻译可以减少API调用时间</li>
                        </ul>
                    </div>
                </div>
            `;
            errorElement.className = 'error-message rate-limit-error';
            errorElement.style.display = 'block';
        }
    }

    // 开始重试倒计时
    startRetryCountdown(waitTime) {
        const countdownElement = document.getElementById('countdown-timer');
        let remainingTime = waitTime;
        
        const countdownInterval = setInterval(() => {
            remainingTime--;
            if (countdownElement) {
                countdownElement.textContent = remainingTime;
            }
            
            if (remainingTime <= 0) {
                clearInterval(countdownInterval);
                this.hideError();
                // 可选：自动重试翻译
                // this.autoRetryTranslation();
            }
        }, 1000);
    }

    // 自动重试翻译（可选功能）
    async autoRetryTranslation() {
        const originalTextElement = document.getElementById('original-text');
        const originalText = originalTextElement.textContent.trim();
        if (originalText) {
            console.log('自动重试翻译...');
            await this.translateText();
        }
    }
    
    // 复制翻译结果
    async copyTranslation() {
        const translatedText = document.getElementById('translated-text').textContent;
        if (translatedText && translatedText !== '正在翻译...' && translatedText !== '翻译失败') {
            try {
                await navigator.clipboard.writeText(translatedText);
                this.showSuccess('译文已复制到剪贴板');
            } catch (error) {
                console.error('复制失败:', error);
                this.showError('复制失败');
            }
        }
    }
    
    // 开始总结页面（新的方法，替换showSummarizeSection）
    async startSummarizing() {
        // 显示加载状态
        document.getElementById('summarize-prompt').style.display = 'none';
        document.getElementById('summarize-loading').style.display = 'flex';
        document.getElementById('summarize-result').style.display = 'none';
        
        // 获取页面内容
        try {
            const response = await chrome.runtime.sendMessage({ type: 'GET_PAGE_CONTENT' });
            
            if (response && response.success) {
                this.pageContent = response.content;
                await this.summarizePage();
            } else {
                throw new Error('获取页面内容失败');
            }
        } catch (error) {
            console.error('获取页面内容失败:', error);
            this.showError('获取页面内容失败');
            // 重置到提示状态
            document.getElementById('summarize-prompt').style.display = 'block';
            document.getElementById('summarize-loading').style.display = 'none';
        }
    }
    
    // 总结页面
    async summarizePage() {
        // 如果没有页面内容，先获取
        if (!this.pageContent) {
            await this.startSummarizing();
            return;
        }
        
        const summaryTextElement = document.getElementById('summary-text');
        const pageTitleElement = document.getElementById('page-title');
        
        // 显示总结内容区域
        document.getElementById('summarize-prompt').style.display = 'none';
        document.getElementById('summarize-loading').style.display = 'flex';
        document.getElementById('summarize-result').style.display = 'none';
        
        // 显示页面标题
        pageTitleElement.textContent = this.pageContent.title || '无标题';
        summaryTextElement.textContent = '正在分析页面内容...';
        
        try {
            const messages = [
                {
                    role: 'system',
                    content: '你是一个专业的内容总结助手。请对用户提供的网页内容进行简洁、准确的总结，突出重点信息。'
                },
                {
                    role: 'user',
                    content: `请总结以下网页内容：\n\n标题：${this.pageContent.title}\n\n内容：${this.pageContent.content}`
                }
            ];
            
            const response = await chrome.runtime.sendMessage({
                type: 'CALL_AI_API',
                data: {
                    apiKey: window.configManager.getApiKey(), // 向后兼容
                    messages: messages,
                    model: window.configManager.getModel(),
                    maxTokens: window.configManager.getMaxTokens(),
                    providers: window.configManager.config.providers || {}
                }
            });
            
            if (response && response.success) {
                summaryTextElement.textContent = response.data;
                
                // 隐藏加载状态，显示结果
                document.getElementById('summarize-loading').style.display = 'none';
                document.getElementById('summarize-result').style.display = 'block';
                
                this.hideError();
            } else {
                throw new Error(response.error || '总结失败');
            }
        } catch (error) {
            console.error('总结失败:', error);
            summaryTextElement.textContent = '总结失败';
            
            // 隐藏加载状态，显示结果（即使失败也要显示）
            document.getElementById('summarize-loading').style.display = 'none';
            document.getElementById('summarize-result').style.display = 'block';
            
            this.showError(error.message || '总结失败');
        }
    }
    
    // 复制总结结果
    async copySummary() {
        const summaryText = document.getElementById('summary-text').textContent;
        if (summaryText && summaryText !== '正在分析页面内容...' && summaryText !== '总结失败') {
            try {
                await navigator.clipboard.writeText(summaryText);
                this.showSuccess('总结已复制到剪贴板');
            } catch (error) {
                console.error('复制失败:', error);
                this.showError('复制失败');
            }
        }
    }
    
    // 显示指定区域
    showSection(sectionName) {
        // 隐藏所有区域
        const sections = ['config', 'main', 'settings'];
        sections.forEach(section => {
            const element = document.getElementById(`${section}-section`);
            if (element) {
                element.style.display = 'none';
            }
        });
        
        // 显示指定区域
        const targetElement = document.getElementById(`${sectionName}-section`);
        if (targetElement) {
            targetElement.style.display = 'block';
            this.currentSection = sectionName;
            
            // 如果显示主界面且当前在翻译标签页，启动监听
            if (sectionName === 'main') {
                const translateTab = document.getElementById('translate-tab');
                if (translateTab && translateTab.classList.contains('active')) {
                    if (!this.selectionMonitorInterval) {
                        this.startTextSelectionMonitor();
                    }
                }
            } else {
                // 如果离开主界面，停止监听
                this.stopTextSelectionMonitor();
            }
        }
    }
    
    // 显示错误信息
    showError(message) {
        const errorElement = document.getElementById('error-message');
        errorElement.textContent = message;
        errorElement.style.display = 'flex';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            this.hideError();
        }, 3000);
    }
    
    // 隐藏错误信息
    hideError() {
        const errorElement = document.getElementById('error-message');
        errorElement.style.display = 'none';
    }
    
    // 显示成功信息
    showSuccess(message) {
        // 创建成功消息元素
        const successElement = document.createElement('div');
        successElement.className = 'success-message';
        successElement.textContent = message;
        successElement.style.display = 'flex';
        
        // 添加到页面
        const mainContent = document.querySelector('.main-content');
        mainContent.appendChild(successElement);
        
        // 3秒后自动隐藏
        setTimeout(() => {
            successElement.remove();
        }, 3000);
    }

    // 测试API连接
    async testApiConnection(providerName) {
        const apiKeyInput = document.getElementById(`${providerName}-api-key`);
        const baseUrlInput = document.getElementById(`${providerName}-base-url`);
        const testButton = document.getElementById(`test-${providerName}-btn`);
        const testStatus = document.getElementById(`${providerName}-test-status`);
        
        const apiKey = apiKeyInput.value.trim();
        const baseUrl = baseUrlInput.value.trim();
        
        if (!apiKey) {
            testStatus.textContent = '请先输入API密钥';
            testStatus.className = 'test-status error';
            return;
        }
        
        // 开始测试
        testButton.disabled = true;
        testButton.textContent = '测试中...';
        testStatus.textContent = '连接测试中...';
        testStatus.className = 'test-status testing';
        
        try {
            const response = await chrome.runtime.sendMessage({
                type: 'TEST_API_CONNECTION',
                data: {
                    provider: providerName,
                    apiKey: apiKey,
                    baseUrl: baseUrl
                }
            });
            
            if (response && response.success) {
                testStatus.textContent = '连接成功 ✓';
                testStatus.className = 'test-status success';
                
                // 记录测试通过的服务商
                this.testedProviders.add(providerName);
                
                // 更新模型选择器，显示该服务商的模型
                this.updateAvailableModels();
                
                // 连接成功后检测免费模型
                setTimeout(() => this.detectFreeModels(providerName, apiKey, baseUrl), 1000);
            } else {
                testStatus.textContent = response.error || '连接失败';
                testStatus.className = 'test-status error';
                
                // 移除失败的服务商
                this.testedProviders.delete(providerName);
                this.updateAvailableModels();
            }
        } catch (error) {
            console.error('测试API连接失败:', error);
            testStatus.textContent = '测试失败';
            testStatus.className = 'test-status error';
            
            // 移除失败的服务商
            this.testedProviders.delete(providerName);
            this.updateAvailableModels();
        } finally {
            testButton.disabled = false;
            testButton.textContent = '测试连接';
        }
    }
    
    // 检测免费模型
    async detectFreeModels(providerName, apiKey, baseUrl) {
        try {
            const response = await chrome.runtime.sendMessage({
                type: 'DETECT_FREE_MODELS',
                data: {
                    provider: providerName,
                    apiKey: apiKey,
                    baseUrl: baseUrl
                }
            });
            
            if (response && response.success && response.models && response.models.length > 0) {
                console.log(`检测到${providerName}的免费模型:`, response.models);
                this.updateModelOptions(providerName, response.models);
                
                // 显示检测结果
                const testStatus = document.getElementById(`${providerName}-test-status`);
                if (testStatus) {
                    testStatus.textContent = `发现${response.models.length}个免费模型 🎁`;
                    testStatus.className = 'test-status info';
                }
            }
        } catch (error) {
            console.error('检测免费模型失败:', error);
        }
    }
    
    // 更新模型选择选项
    updateModelOptions(providerName, freeModels) {
        // 存储免费模型信息
        if (!this.availableFreeModels) {
            this.availableFreeModels = [];
        }
        
        // 移除该服务商之前的免费模型
        this.availableFreeModels = this.availableFreeModels.filter(m => m.provider !== providerName);
        
        // 添加新检测到的免费模型
        if (freeModels && freeModels.length > 0) {
            this.availableFreeModels.push(...freeModels);
            console.log(`${providerName} 可用免费模型:`, freeModels);
        }
        
        // 重新更新模型选择器
        this.updateAvailableModels();
        
        // 显示检测结果
        const testStatus = document.getElementById(`${providerName}-test-status`);
        if (testStatus && freeModels && freeModels.length > 0) {
            testStatus.textContent = `发现${freeModels.length}个免费模型 🎁`;
            testStatus.className = 'test-status info';
        }
    }

    // 更新语言检测显示
    updateLanguageDetection() {
        const originalTextElement = document.getElementById('original-text');
        const translationDirection = document.getElementById('translation-direction');
        const languageDirectionText = document.getElementById('language-direction-text');
        
        if (!originalTextElement || !translationDirection || !languageDirectionText) return;
        
        const text = originalTextElement.textContent.trim();
        
        if (text.length === 0) {
            // 没有文本时隐藏方向显示
            translationDirection.style.display = 'none';
            translationDirection.classList.remove('active');
            return;
        }
        
        if (text.length < 2) {
            // 文本太短时显示检测中
            translationDirection.style.display = 'flex';
            translationDirection.classList.remove('active');
            languageDirectionText.textContent = '输入更多文本以检测语言...';
            return;
        }
        
        // 检测语言并显示翻译方向
        const detectedLanguage = this.detectLanguage(text);
        const languageNames = {
            'zh': '中文',
            'en': '英文', 
            'ja': '日文',
            'ko': '韩文'
        };
        
        const sourceLanguageName = languageNames[detectedLanguage] || '未知语言';
        const targetLanguageName = detectedLanguage === 'zh' ? '英文' : '中文';
        
        translationDirection.style.display = 'flex';
        translationDirection.classList.remove('active'); // 不加active类，避免动画
        languageDirectionText.textContent = `${sourceLanguageName} → ${targetLanguageName}`;
        
        // 重置箭头动画
        const arrow = translationDirection.querySelector('.direction-arrow');
        if (arrow) {
            arrow.style.animation = 'none';
        }
    }

    // 更新可用模型列表（只显示测试通过的服务商的模型）
    updateAvailableModels() {
        const configModelSelect = document.getElementById('model-select');
        const translateModelSelect = document.getElementById('translate-model-select');
        
        [configModelSelect, translateModelSelect].forEach(select => {
            if (!select) return;
            
            // 清空现有选项
            select.innerHTML = '';
            
            // 定义所有可能的模型
            const allModels = {
                'moonshot': {
                    label: 'Moonshot (Kimi)',
                    models: [
                        { value: 'moonshot-v1-8k', text: 'moonshot-v1-8k (推荐)', type: 'paid' },
                        { value: 'moonshot-v1-32k', text: 'moonshot-v1-32k', type: 'paid' },
                        { value: 'moonshot-v1-128k', text: 'moonshot-v1-128k', type: 'paid' }
                    ]
                },
                'openai': {
                    label: 'OpenAI',
                    models: [
                        { value: 'gpt-4o-mini', text: 'GPT-4o Mini', type: 'paid' },
                        { value: 'gpt-4o', text: 'GPT-4o', type: 'paid' },
                        { value: 'gpt-3.5-turbo', text: 'GPT-3.5 Turbo', type: 'paid' }
                    ]
                },
                'anthropic': {
                    label: 'Anthropic',
                    models: [
                        { value: 'claude-3-haiku', text: 'Claude 3 Haiku', type: 'paid' },
                        { value: 'claude-3-sonnet', text: 'Claude 3 Sonnet', type: 'paid' },
                        { value: 'claude-3-opus', text: 'Claude 3 Opus', type: 'paid' }
                    ]
                }
            };
            
            // 如果没有测试通过的服务商，显示提示
            if (this.testedProviders.size === 0) {
                const promptGroup = document.createElement('optgroup');
                promptGroup.label = '请先测试API连接';
                
                const promptOption = document.createElement('option');
                promptOption.value = '';
                promptOption.textContent = '请先在设置中测试API连接';
                promptOption.disabled = true;
                promptGroup.appendChild(promptOption);
                
                select.appendChild(promptGroup);
                return;
            }
            
            // 分别为每个服务商创建免费和付费分组
            this.testedProviders.forEach(providerName => {
                const providerInfo = allModels[providerName];
                if (!providerInfo) return;
                
                // 获取该服务商的免费模型
                const freeModels = this.availableFreeModels ? 
                    this.availableFreeModels.filter(m => m.provider === providerName) : [];
                
                // 如果有免费模型，先创建免费模型组
                if (freeModels.length > 0) {
                    const freeOptgroup = document.createElement('optgroup');
                    freeOptgroup.label = `${providerInfo.label} - 免费`;
                    
                    freeModels.forEach(model => {
                        const option = document.createElement('option');
                        option.value = model.id;
                        option.textContent = this.getSelectOptionText(model.id, true);
                        option.title = `${model.name} (免费模型)`; // 添加提示信息
                        freeOptgroup.appendChild(option);
                    });
                    
                    select.appendChild(freeOptgroup);
                }
                
                // 创建付费模型组 - 过滤掉已在免费模型中的重复项
                const paidOptgroup = document.createElement('optgroup');
                paidOptgroup.label = `${providerInfo.label} - 付费`;
                
                // 获取免费模型的ID列表，用于去重
                const freeModelIds = freeModels.map(m => m.id);
                
                providerInfo.models.forEach(model => {
                    // 跳过已在免费模型组中出现的模型
                    if (freeModelIds.includes(model.value)) {
                        return;
                    }
                    
                    const option = document.createElement('option');
                    option.value = model.value;
                    option.textContent = this.getSelectOptionText(model.value, false);
                    option.title = `${model.text} (付费模型)`; // 添加提示信息
                    paidOptgroup.appendChild(option);
                });
                
                // 只有当付费组有选项时才添加
                if (paidOptgroup.children.length > 0) {
                    select.appendChild(paidOptgroup);
                }
            });
            
            // 设置默认选项 - 优先选择免费模型
            if (select.options.length > 0) {
                let defaultValue = '';
                
                // 首先尝试选择免费模型
                if (this.availableFreeModels && this.availableFreeModels.length > 0) {
                    defaultValue = this.availableFreeModels[0].id;
                } else {
                    // 没有免费模型时，优先选择moonshot付费模型
                    for (let i = 0; i < select.options.length; i++) {
                        const option = select.options[i];
                        if (option.value && option.value.startsWith('moonshot-')) {
                            defaultValue = option.value;
                            break;
                        }
                    }
                    
                    // 如果没有moonshot，选择第一个可用的
                    if (!defaultValue) {
                        for (let i = 0; i < select.options.length; i++) {
                            if (select.options[i].value) {
                                defaultValue = select.options[i].value;
                                break;
                            }
                        }
                    }
                }
                
                if (defaultValue) {
                    select.value = defaultValue;
                    
                    // 更新翻译模型状态显示
                    if (select.id === 'translate-model-select') {
                        this.updateModelStatus(defaultValue);
                    }
                }
            }
        });
    }

    // 检查已配置的服务商
    async checkConfiguredProviders() {
        const config = window.configManager.config;
        const providers = config.providers || {};
        
        for (const [providerName, provider] of Object.entries(providers)) {
            if (provider.configured && provider.apiKey) {
                console.log(`检查${providerName}服务商连通性...`);
                
                try {
                    const response = await chrome.runtime.sendMessage({
                        type: 'TEST_API_CONNECTION',
                        data: {
                            provider: providerName,
                            apiKey: provider.apiKey,
                            baseUrl: provider.baseUrl
                        }
                    });
                    
                    if (response && response.success) {
                        console.log(`${providerName}连接正常`);
                        this.testedProviders.add(providerName);
                        
                        // 自动检测免费模型
                        setTimeout(() => {
                            this.detectFreeModels(providerName, provider.apiKey, provider.baseUrl);
                        }, 500);
                    } else {
                        console.log(`${providerName}连接失败:`, response?.error);
                    }
                } catch (error) {
                    console.error(`检查${providerName}连通性失败:`, error);
                }
            }
        }
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new SmartAssistant();
}); 